<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Company extends Controller 
{
    
	private function setVars()
	{
		$this->tpl['title'] = "Company info";
        $this->tpl['sidebar'] = $this->tm->randomBlock();
		$this->tpl['head'] = '';
        $this->tpl['body'] = '';
        
        $this->tm->db_table = $this->db_table = 'contact_org';
        $this->tm->uid = $this->uid = $this->tm->get_uid();

        define('URI',$this->uri->segment(1).'/'.$this->uri->segment(2));

        $this->org_types = array(
                                'For-Profit' => 'For-Profit',
                                'Government' => 'Government',
                                'Nonprofit' => 'Nonprofit'
                            );
	}
	
	function __construct()
	{
		parent::Controller();
        $this->auth->CheckTaMeR(100,2);
        $this->load->model('Tamer_Model', 'tm');
		$this->setVars();
        //$this->load->library('profiler');
        log_message('debug', "Control Panel->Company: Controler Class Initialized");
	}
    
    /**
    * @note	index
    * @info	Just forwarding
    * @author	Dennis T. Kaplan
    * @access	public
    * @param	 
    * @return	html page
    */	
    public function index()
    {
        $this->db_id = $this->tm->get_Org_id();
        $this->db_data = $this->tm->init_db($this->db_id);
        if($this->input->post('save') !== FALSE)
        {
            if($this->validate() === TRUE)
            {
            	$this->save();
            }
        }
        $this->form();
    }
    
    /**
    * @note	form
    * @info	Create Form in Table 
    * @author	Dennis T. Kaplan
    * @access	public
    * @param	 
    * @return	html
    */	
    private function form()
    {
        $this->tpl['tpljs'][]  = 'jquery';
        $this->tpl['tpljs'][]  = 'jquery.bgiframe.min';
        $this->tpl['tpljs'][]  = 'jquery.dimensions';
        $this->tpl['tplcss'][]  = 'jquery.autocomplete';
        $this->tpl['tpljs'][]  = 'jquery.autocomplete';
        $this->tpl['tpljs'][]  = 'postcode';
        $this->load->library('pquery');
        $action = $this->uri->segment(3);
        $oid = $this->uri->segment(4);
        
        extract($this->db_data);
        
        $attributes = array('name' => 'company');
        $this->load->helper('form');
        
        $class='';
        if(isset($this->validation->Name_error)){
            $class='FormErr'; 
        }
        $form['Organization Name'] = form_input(array(
        'name'        => 'Name',
        'id'          => 'Name',
        'value'       =>  $Name,
        'maxlength'   => '50',
        'size'        => '30',
        'class'       => $class
        )
        );
        $form['Org Type'] = form_dropdown('Org_Type', $this->org_types);//, $this->db_data->Org_Type
        
        $class='';
        if(isset($this->validation->Street_error)){
            $class='FormErr'; 
        }
        $form['Street'] = form_input(array(
        'name'        => 'Street',
        'id'          => 'Street',
        'value'       => $Street,
        'maxlength'   => '50',
        'size'        => '30',
        'class'       => $class
        )
        );

        $code = '';
        if($Postcode > 0){
            $query = $this->db->getwhere('places_postcode', array('id' => $Postcode), 1);
            if ($query->num_rows() > 0) {
                $v = $query->row();
            $code = "$v->code $v->city $v->state" ;
            $this->tpl['body'] .= '<script type="text/javascript">'.$this->pquery->hide('#Postcode').'</script>';
            }else{
                $code = 'Click here and select location with mouse';
            }
        }
        
        $class='';
        if(isset($this->validation->Postcode_error)){
            $class='FormErr'; 
        }

        $form['Postcode or City'] =  form_input(array(
                    'name'        => 'Postcode',
                    'id'          => 'Postcode',
                    'value'       => $Postcode,
                    'size'        => '10',
                    'class'       => $class,
                    'onclick'     => 'clearValue(this)'
                    )
                    ).'<span id="postresult"><a href="#" onclick= "editzip(this)">'.$code.'</a></span>';


        $class='';
        if(isset($this->validation->Phone_error)){
            $class='FormErr'; 
        }
        $form[1]['Phone'] = form_input(array(
        'name'        => 'Phone',
        'id'          => 'Phone',
        'value'       =>  $Phone,
        'maxlength'   => '15',
        'size'        => '15',
        'class'       => $class
        )
        );

        $class='';
        if(isset($this->validation->FAX_error)){
            $class='FormErr'; 
        }
        $form[1]['FAX'] = form_input(array(
        'name'        => 'FAX',
        'id'          => 'FAX',
        'value'       =>  $FAX,
        'maxlength'   => '20',
        'size'        => '13',
        'class'       => $class
        )
        );

        $class='';
        if(isset($this->validation->Website_error)){
            $class='FormErr'; 
        }
        $form['Website'] = form_input(array(
        'name'        => 'Website',
        'id'          => 'Website',
        'value'       =>  $Website,
        'maxlength'   => '60',
        'size'        => '40',
        'class'       => $class
        )
        );
        
        
        $class='';
        if(isset($this->validation->Notes_error)){
            $class='FormErr'; 
        }
        $form['Notes'] = form_textarea(array(
        'name'        => 'Notes',
        'id'          => 'Notes',
        'value'       =>  $Notes,
        'rows'        => '10',
        'cols'        => '50',
        'class'       => $class
        )
        );
        
        $form[''] = form_submit(array(
        'name'        => 'save',
        'class'       => 'submit',
        'value'       => 'Save',
        'style'       => 'margin:10px'
        )
        );
        $this->load->library('table');
        $this->tpl['body'] .= form_open(URI, $attributes);
        $this->tpl['body'] .= $this->table->form_table($form);
        $this->tpl['body'] .= '</form>';

        if($Postcode > 0){
            $this->tpl['body'] .= '<script type="text/javascript">'.$this->pquery->hide('#Postcode').'</script>';
        }
        $this->load->view('blank', $this->tpl);
    }
    
    /**
    * @note	validate
    * @info	Validate submited form
    * @author	Dennis T. Kaplan
    * @access	private
    * @param	 
    * @return	TRUE || FALSE
    */	
    private function validate()
    {
        log_message('debug', 'Company: Validation initiated');
        $this->load->library('validation');
		$rules['Name']			= "trim|required|min_length[5]|max_length[50]|xss_clean";
		$rules['Org_Type']		= "trim|required|xss_clean";
        $rules['Street']		= 'trim|required|min_length[5]|max_length[50]|xss_clean';
        $rules['Postcode']	    = 'callback_postcode_check';
        $rules['Phone']		    = 'trim|required|max_length[20]';
        $rules['FAX']		    = 'trim|max_length[15]';
        $rules['Website']		= 'trim|required|min_length[6]|max_length[200]|xss_clean|prep_url';
        $rules['Notes']  		= "trim|max_length[2000]|xss_clean";
        
        $this->validation->set_rules($rules);
        $valResult = $this->validation->run();

        delids($this->db_data);
        $this->post = array();
        $count = 0;
        foreach($this->db_data as $k => $v){
            if(isset($this->validation->$k)){
                $p = $this->validation->$k;

                if($p != $v){
                    $count++;
                    if($k == 'Phone' || $k == 'FAX'){
                        $this->post[$k] = format_phone($p);
                    }else{
                        $this->post[$k] = $p;
                    }
                }
            }else{
                if(!isset($this->post[$k]) && $v != ''){
                    $count++;
                    $this->post[$k] = '';
                }
            }
        }
        $this->db_data = array_merge($this->db_data, $this->post);
        if($count == 0)
        {
            $this->msg->setError('Not Updated');
            $this->msg->setMsg('You have not made any changes.');
            return FALSE;
        }elseif($valResult != 1){
            return FALSE;
        }elseif($count > 0){
            return TRUE;
        }
    }

    function postcode_check($str)
	{
		if ($str < 10000000 || $str > 20000000)
		{
            $this->validation->set_message('postcode_check', 'You must select the %s with the mouse from the list');
			return FALSE;
		}
		else
		{
            $this->validation->Postcode = $str;
			return TRUE;
		}
	}

    private function save()
    {
        if($this->db_id !== FALSE)
        {
            log_message('info', 'update id: '. $this->db_id);
            $this->db->where('id', $this->db_id);
            $this->db->update($this->db_table, $this->post);
            $this->msg->setMsg('Your record has been updated');
        }else{
            
            $this->db->insert($this->db_table, $this->post);
            $this->db_id = $this->db->insert_id();
            $sql = "INSERT INTO `contact_user_org` (`id`, `user_id`, `org_id`) VALUES (NULL, '$this->uid', '$this->db_id');";
            $this->db->query($sql);
            log_message('info', 'insert id: '. $this->db_id);
            $this->msg->setMsg('Your record has been added');
        }
    }

}

?>
